﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.Threading;
using System.Timers;

namespace auxiliary_proj
{

    public partial class MainForm : Form
    {
        UCPurchaseOrder PurchaseOrderContent;
        UCViewVendor ucVendors;
        UCOrderStatus OrderStatus;
        UCReport ReportsContent;
        UCInventory InventoryContent;
        UCUnits ucUnits;
        Home HomeContent;

        //Server stuff
        private static MySqlConnection DBCon;

        //timer to requery order status count every 5 seconds
        public System.Windows.Forms.Timer orderStatus_timer;

        //timer for inactivity logout
        public System.Windows.Forms.Timer idle_timer;
        public int idleTime = 15 * 60;//in seconds

        public MainForm()
        {
            Thread thread = new Thread(new ThreadStart(SplashScreen));
            thread.Start();
            Thread.Sleep(3000);
            InitializeComponent();
            thread.Abort();
            HomeContent = Singleton.getHome();
            HomeContent.tbUserName.Focus();
            this.pnlMain.Controls.Add(HomeContent);
            HomeContent.ActiveControl = HomeContent.tbUserName;
            setFunctionality();
            Program.parseServerInfo();
            DBCon = new MySqlConnection(Program.getConnection());


            //timer stuff
            orderStatus_timer = new System.Windows.Forms.Timer();
            orderStatus_timer.Interval = 5000;// += new ElapsedEventHandler(orderStatus_timer_Elapsed);
            orderStatus_timer.Tick += new EventHandler(orderStatus_timer_Elapsed);

            //set a timer where it calls _idleTick after timer expires (logout) after 15min
            idle_timer = new System.Windows.Forms.Timer();
            idle_timer.Interval = (idleTime * 1000);
            idle_timer.Tick += new EventHandler(idle_timer_Tick);
            //enable this timer on login

            this.MouseMove += new MouseEventHandler(this_MouseMove);

            //not yet - after user logs in -- incase server info doesn't exist yet
            //qInventory();

            this.dataGridInventory.CellContentDoubleClick += new DataGridViewCellEventHandler(dataGridInventory_CellContentDoubleClick);

            MainPODataGridView.AlternatingRowsDefaultCellStyle.BackColor = Color.Beige;
        }

        public void SplashScreen()
        {
            Application.Run(new SplashScreen());
        }

        //Main Form getters/setters
        public int ucPurchaseOrderSubmit
        {
            get { return this.MainTabControl.SelectedIndex; }
            set { this.MainTabControl.SelectedIndex = value; }
        }

        /************************************
         *    CLICK EVENTS FOR MENU BAR     *
         * **********************************/

        private void purchaseOrderReportToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ReportsContent = Singleton.getUCReport();
            this.pnlMain.Controls.Clear();
            ReportsContent.setTab(0); //set to first tab on click for P.O.
            this.pnlMain.Controls.Add(ReportsContent);
        }

        private void salesOrderReportToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ReportsContent = Singleton.getUCReport();
            this.pnlMain.Controls.Clear();
            ReportsContent.setTab(1);  //set to 2nd tab on click for Sales Order
            this.pnlMain.Controls.Add(ReportsContent);

        }

        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Singleton.showForm<FormNewMessage>(Application.OpenForms);
        }

        private void sentToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Singleton.showForm<FormSentMessage>(Application.OpenForms);
        }

        private void CreateUserBtn_Click(object sender, EventArgs e)
        {
            createNewUser();
        }

        private void CreateUnitBtn_Click(object sender, EventArgs e)
        {
            createNewUnit();
        }

        private void CreatePoBtn_Click(object sender, EventArgs e)
        {
            if (PurchaseOrderContent == null) //allows for the contents to remain after leaving and returning
                PurchaseOrderContent = Singleton.getUCPurchaseOrder();
            this.pnlMain.Controls.Clear();
            this.pnlMain.Controls.Add(PurchaseOrderContent);
        }

        private void HomeBtn_Click(object sender, EventArgs e)
        {
            HomeContent = Singleton.getHome();
            this.pnlMain.Controls.Clear();
            HomeContent.pWelcome.Location = new Point(this.pnlMain.Width / 2 - HomeContent.pLogin.Width / 2, this.pnlMain.Height / 2 - HomeContent.pLogin.Height / 2);
            HomeContent.pLogin.Location = new Point(this.pnlMain.Width / 2 - HomeContent.pLogin.Width / 2, this.pnlMain.Height / 2 - HomeContent.pLogin.Height / 2);
            this.pnlMain.Controls.Add(HomeContent);
        }

        private void OrderStatusBtn_Click(object sender, EventArgs e)
        {
            OrderStatus = Singleton.getUCOrderStatus();
            this.pnlMain.Controls.Clear();
            Singleton.getUCOrderStatus().qSalesOrder();
            this.pnlMain.Controls.Add(OrderStatus);
        }

        private void InventoryBtn_Click(object sender, EventArgs e)
        {
            InventoryContent = Singleton.getUCInventory();
            this.pnlMain.Controls.Clear();
            InventoryContent.qInventory();
            Singleton.getMainForm().qInventory();
            this.pnlMain.Controls.Add(InventoryContent);
        }

        private void POReportBtn_Click(object sender, EventArgs e)
        {
            ReportsContent = Singleton.getUCReport();
            this.pnlMain.Controls.Clear();
            ReportsContent.setTab(0); //set tab on Reports Control to P.O.
            this.pnlMain.Controls.Add(ReportsContent);
        }

        private void SalesReportBtn_Click(object sender, EventArgs e)
        {
            ReportsContent = Singleton.getUCReport();
            this.pnlMain.Controls.Clear();
            ReportsContent.setTab(1); //set tab on Reports Control to Sales Order
            this.pnlMain.Controls.Add(ReportsContent);
        }

        public void setTab(int tab)
        {
            MainTabControl.SelectedIndex = tab;
        }

        private void viewItemToolStripMenuItem_Click(object sender, EventArgs e)
        {
            InventoryContent = Singleton.getUCInventory();
            this.pnlMain.Controls.Clear();
            InventoryContent.qInventory();
            Singleton.getMainForm().qInventory();
            this.pnlMain.Controls.Add(InventoryContent);
        }

        private void btnViewUnit_Click(object sender, EventArgs e)
        {
            ucUnits = Singleton.getUCUnits();
            this.pnlMain.Controls.Clear();
            ucUnits.viewUnits();
            this.pnlMain.Controls.Add(ucUnits);
        }

        //timer order status
        int prev = 0;
        int curr = 0;
        private void orderStatus_timer_Elapsed(object sender, EventArgs e)
        {
            prev = curr;
            if (Employee.Permission == 2)
            {
                qNewPendingSalesOrderCount();
            }

            else if (Employee.Permission == 1)
            {
                qNewActiveSalesOrderCount();
            }

            //get new current value, find out if new
            if (curr - prev > 0)
            //new order show popup
            {
                OrderStatusNotifyIcon.ShowBalloonTip(5000);
            }

            orderStatus_timer.Start();
        }

        MySqlConnection conn;
        MySqlCommand comm;
        public void qNewPendingSalesOrderCount()
        {
            Singleton.getMainForm().lbSalesOrder.Show();
            conn = new MySqlConnection(Program.getConnection());
            string query = "SELECT COUNT(status) FROM S_ORDER WHERE status<>'3'";
            comm = new MySqlCommand(query, conn);
            try
            {
                conn.Open();
                try
                {
                    MySqlDataReader reader = comm.ExecuteReader();
                    reader.Read();
                    Int32 count = Int32.Parse(reader[0].ToString());
                    curr = count;
                    if (count > 0)
                    {
                        Singleton.getMainForm().lbSalesOrder.Text = "" + count;
                    }
                    else
                    {
                        Singleton.getMainForm().lbSalesOrder.Hide();
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
            finally
            {
                conn.Close();
            }

        }

        public void qNewActiveSalesOrderCount()
        {
            Singleton.getMainForm().lbSalesOrder.Show();
            conn = new MySqlConnection(Program.getConnection());
            string query = "SELECT COUNT(status) FROM S_ORDER WHERE status='1'";
            comm = new MySqlCommand(query, conn);
            try
            {
                conn.Open();
                try
                {
                    MySqlDataReader reader = comm.ExecuteReader();
                    reader.Read();
                    Int32 count = Int32.Parse(reader[0].ToString());
                    curr = count;
                    if (count > 0)
                    {
                        Singleton.getMainForm().lbSalesOrder.Text = "" + count;
                    }
                    else
                    {
                        Singleton.getMainForm().lbSalesOrder.Hide();
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
            finally
            {
                conn.Close();
            }
        }

        //////////////////////////////////////////////////////////////////////
        ///////////////////////////   TIMER EVENTS      //////////////////////
        //////////////////////////////////////////////////////////////////////
        private void this_MouseMove(object sender, MouseEventArgs e)
        {
            Console.Out.WriteLine("Mouse Listener: " + e.Location.ToString());
            //reset timer
            Console.Out.WriteLine(idle_timer.ToString());
            idle_timer.Stop();
            idle_timer.Interval = idleTime * 1000;
            idle_timer.Start();
            Console.Out.WriteLine(idle_timer.ToString());
        }

        private void idle_timer_Tick(object sender, EventArgs e)
        {
            Employee.logout();

            //the timer expired, logout user
            MessageBox.Show("You have been idle for " + (idleTime / 60) + " minutes. Logging out!");
        }

        //override WndProc to reset timer for logout
        protected override void WndProc(ref Message m)
        {
            //Msg 295 is more than likely refresh (did Console.out.writeline(m) and Msg 295 was contantly writing to output
            if (m.Msg != 295)
            {
                if (Employee.Permission != 0)
                {
                    idle_timer.Stop();
                    idle_timer.Interval = idleTime * 1000;
                    idle_timer.Start();
                }
            }

            base.WndProc(ref m);
        }

        //Functionality Set based on user access level
        internal void setFunctionality()
        {
            //guest, not logged in
            if (Employee.Permission == 0)
            {
                setAllFunctionality(false);
                this.btnHome.Enabled = true;
                this.menuUserLogin.Enabled = true;
                this.menuUserExit.Enabled = true;
                this.MainTabControl.TabPages.Remove(tabPage1);
                this.MainTabControl.TabPages.Remove(tabPage2);
            }
            //normal user of system
            else if (Employee.Permission == 1)
            {
                setAllFunctionality(false);
                this.btnHome.Enabled = true;
                this.homeToolStripMenuItem.Enabled = true;
                this.btnOrderStatus.Enabled = true;
                this.orderStatusToolStripMenuItem.Enabled = true;
                this.createToolStripMenuItem.Enabled = true;
                this.viewToolStripMenuItem.Enabled = true;
                this.btnOutstandingPO.Enabled = false;
                this.purchaseOrderToolStripMenuItem.Enabled = false;
                this.outstandingPOToolStripMenuItem.Enabled = false;
                this.userToolStripMenuItem1.Enabled = true;
                this.menuUserLogout.Enabled = true;
                this.menuUserLogin.Enabled = false;
                this.menuMsg.Enabled = true;

            }
            //admin access of system
            else if (Employee.Permission == 2)
            {
                setAllFunctionality(true);
                this.menuUserLogin.Enabled = false;
                this.MainTabControl.TabPages.Insert(0, tabPage1);
                this.MainTabControl.TabPages.Insert(1, tabPage2);
            }
            else//error disable everything
                setAllFunctionality(false);
        }
        //enable/disable all functionality in Main Form
        private void setAllFunctionality(bool b)
        {
            this.btnHome.Enabled = b;
            this.homeToolStripMenuItem.Enabled = b;
            this.btnOrderStatus.Enabled = b;
            this.orderStatusToolStripMenuItem.Enabled = b;
            this.btnInventory.Enabled = b;
            this.inventoryToolStripMenuItem.Enabled = b;
            this.btnViewUnit.Enabled = b;
            this.unitToolStripMenuItem1.Enabled = b;
            this.btnCreateVendor.Enabled = b;
            this.userToolStripMenuItem1.Enabled = b;
            this.btnCreatePO.Enabled = b;
            this.purchaseOrderToolStripMenuItem.Enabled = b;
            this.btnOutstandingPO.Enabled = b;
            this.btnCreateUnit.Enabled = b;
            this.unitToolStripMenuItem.Enabled = b;
            this.btnCreateUser.Enabled = b;
            this.userToolStripMenuItem.Enabled = b;
            this.vendorToolStripMenuItem.Enabled = b;
            this.vendorToolStripMenuItem1.Enabled = b;
            this.btnReportPO.Enabled = b;
            this.btnReportSales.Enabled = b;
            this.menuUserLogin.Enabled = b;
            this.menuUserLogout.Enabled = b;
            this.menuRep.Enabled = b;
            this.menuRepView.Enabled = b;
            this.menuRepViewPO.Enabled = b;
            this.menuRepViewSales.Enabled = b;
            this.menuMsg.Enabled = b;
            this.createToolStripMenuItem.Enabled = b;
            this.viewToolStripMenuItem.Enabled = b;
        }

        void createNewMessage()
        {
            Singleton.showForm<FormComposeMessage>(Application.OpenForms);
        }

        void createNewUnit()
        {
            Singleton.showForm<FormCreateUnit>(Application.OpenForms);
        }

        void createNewUser()
        {
            Singleton.showForm<FormCreateUser>(Application.OpenForms);
        }

        void createNewVendor()
        {
            Singleton.showForm<FormCreateVendor>(Application.OpenForms);
        }

        public void qInventory()
        {
            string query = "SELECT i.item_id, i.description AS name, c.description AS category, i.actual_price, SUM( iq.quantity ) AS quantity FROM ITEM AS i, ITEM_QUANTITY AS iq, CATEGORY AS c WHERE c.cat_id = i.cat_id AND i.item_id = iq.item_id AND quantity >0 GROUP BY i.item_id ORDER BY name";
            try
            {
                dataGridInventory.DataSource = Query.select(query);
            }
            catch (MySqlException exc) { MessageBox.Show(exc.Message); }
        }

        private void aboutInventoryTrackingSystemToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Singleton.showForm<FormAbout>(Application.OpenForms);
        }

        private void dataGridInventory_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            Singleton.showInvItems((int)dataGridInventory.Rows[e.RowIndex].Cells["item_id"].Value, (string)dataGridInventory.Rows[e.RowIndex].Cells["itemName"].Value, (double)dataGridInventory.Rows[e.RowIndex].Cells["actual_price"].Value);
        }

        private void purchaseOrderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PurchaseOrderContent = Singleton.getUCPurchaseOrder();
            this.pnlMain.Controls.Clear();
            this.pnlMain.Controls.Add(PurchaseOrderContent);
        }

        private void unitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            createNewUnit();
        }

        private void userToolStripMenuItem_Click(object sender, EventArgs e)
        {
            createNewUser();
        }

        private void homeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            HomeContent = Singleton.getHome();
            this.pnlMain.Controls.Clear();
            HomeContent.pWelcome.Location = new Point(this.pnlMain.Width / 2 - HomeContent.pLogin.Width / 2, this.pnlMain.Height / 2 - HomeContent.pLogin.Height / 2);
            HomeContent.pLogin.Location = new Point(this.pnlMain.Width / 2 - HomeContent.pLogin.Width / 2, this.pnlMain.Height / 2 - HomeContent.pLogin.Height / 2);
            this.pnlMain.Controls.Add(HomeContent);
        }

        private void orderStatusToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OrderStatus = Singleton.getUCOrderStatus();
            this.pnlMain.Controls.Clear();
            Singleton.getUCOrderStatus().qSalesOrder();
            this.pnlMain.Controls.Add(OrderStatus);
        }

        private void inventoryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            InventoryContent = Singleton.getUCInventory();
            this.pnlMain.Controls.Clear();
            InventoryContent.qInventory();
            Singleton.getMainForm().qInventory();
            this.pnlMain.Controls.Add(InventoryContent);
        }

        private void unitToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            ucUnits = Singleton.getUCUnits();
            this.pnlMain.Controls.Clear();
            ucUnits.viewUnits();
            this.pnlMain.Controls.Add(ucUnits);
        }

        private void userToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            Singleton.showForm<FormViewUser>(Application.OpenForms);
        }

        private void menuUserLogin_Click(object sender, EventArgs e)
        {
            FormLogin fl = new FormLogin();
            fl.StartPosition = FormStartPosition.CenterScreen;
            fl.Show();
            this.Opacity = .65;
        }

        private void menuUserLogout_Click(object sender, EventArgs e)
        {
            Employee.logout();
        }

        private void menuUserExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void vendorToolStripMenuItem_Click(object sender, EventArgs e)
        {
            createNewVendor();
        }

        private void vendorToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            ucVendors = Singleton.getUCVendors();
            this.pnlMain.Controls.Clear();
            ucVendors.viewVendors();
            this.pnlMain.Controls.Add(ucVendors);
        }

        private void btnCreateVendor_Click(object sender, EventArgs e)
        {
            createNewVendor();
        }

        private void grid_DoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            DataGridViewRow row = ((DataGridView)sender).Rows[e.RowIndex];

            Console.Out.WriteLine(row.ToString());

            FormViewPODetails exists = Application.OpenForms.OfType<FormViewPODetails>().FirstOrDefault();
            if (exists == null)
            {
                FormViewPODetails poDetails = new FormViewPODetails(row);
                poDetails.StartPosition = FormStartPosition.CenterScreen;
                poDetails.Show();
            }
            else
            {
                exists.Close();
                exists.Dispose();
                FormViewPODetails poDetails = new FormViewPODetails(row);
                poDetails.StartPosition = FormStartPosition.CenterScreen;
                poDetails.Show();
            }
        }

        private void newMsgToolTip_Click(object sender, EventArgs e)
        {
            createNewMessage();
        }

        private void btnOutstandingPO_Click(object sender, EventArgs e)
        {
            Singleton.showForm<FormViewPO>(Application.OpenForms);
        }

        private void outstandingPOToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Singleton.showForm<FormViewPO>(Application.OpenForms);
        }
    }
}
